﻿using System;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;


namespace Project.DAO
{
    public class DataProvider
    {

        public static string dbConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BLiS.mdf;Integrated Security=True;User Instance=True";        
        public string dbProviderName = "System.Data.SqlClient";


        public DbCommand CreateCommand()
        {
            string strConnectionString = dbConnectionString;
            string strProviderName = dbProviderName;

            DbProviderFactory factory = DbProviderFactories.GetFactory(strProviderName);
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = strConnectionString;
            DbCommand command = connection.CreateCommand();
            return command;
        }

        public DataTable ExecuteSelectCommand(DbCommand command) //Select
        {
            DataTable table = null;
            try
            {
                command.Connection.Open();
                DbDataReader reader = command.ExecuteReader();
                table = new DataTable();
                table.Load(reader);
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
                // xu ly cac exceptions sau
            }
            finally
            {
                command.Connection.Close();
            }
            return table;
        }

        public void ExecuteNonQueryCommand(DbCommand command)//Insert, delete, update 
        {
            try
            {
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
                // xu ly cac exceptions sau
            }
            finally
            {
                command.Connection.Close();
            }
        }
        
        public object ExecScalarQueryCommand(DbCommand command)
        {
            object o = null;
            try
            {
                command.Connection.Open();
                o = command.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw ex;
                // xu ly cac exceptions sau
            }
            finally
            {
                command.Connection.Close();
            }
            return o;
        }
    }
    
}